package com.ydy.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class ErrorZuulFilter extends ZuulFilter {


    private static Logger LOGGER = LoggerFactory.getLogger(ErrorZuulFilter.class);

    /**
     * 网关类型
     */
    @Override
    public String filterType() {
        return "error";
    }

    /**
     * 网关优先级
     */
    @Override
    public int filterOrder() {
        return -1;
    }

    /**
     * 是否开启
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤逻辑
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("error");
        RequestContext ctx = RequestContext.getCurrentContext();
        Object e = ctx.get("throwable");
        ctx.setResponseStatusCode(500);
        if(e!=null && e instanceof ZuulException){
            ZuulException zuulException = (ZuulException)e;
            System.out.println(zuulException.getMessage());
            ctx.setResponseBody(zuulException.getMessage());
        }
        return null;
    }
}
